﻿using Dapper;
using ERPEF;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SkiaSharp;
using System.Data;
using System.Data.SqlClient;

namespace S4Project.Controllers

{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class bs_clientController : ControllerBase
    {
        private readonly MyDbContext myDbContext;

        private readonly bs_clientService _bs_clientService;

        public bs_clientController(MyDbContext myDbContext, bs_clientService bs_clientService)
        {
            this.myDbContext = myDbContext;
            this._bs_clientService = bs_clientService;
        }

        /// <summary>
        /// 客户列表查询
        /// </summary>
        /// <returns></returns>   
        [HttpGet]
        public async Task<List<bs_client>> Index()
        {

            return await _bs_clientService.Query();
        }

        /// <summary>
        /// 客户列添加
        /// </summary>
        /// <returns></returns> 
        [HttpPost]
        public async Task<IActionResult> AddWarehouse(bs_client bs_client)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateWarehouseCode(maxCodeNumber);

            bs_client.W_code = newCode;



            if (ModelState.IsValid)
            {
                int result = await _bs_clientService.Add(bs_client);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.bs_Client
                .Where(w => w.W_code.StartsWith("KH"))
                .Select(w => w.W_code.Substring(2))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "KH0001";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);

            // 生成新的编码数字部
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了9999，则重置为0001
            if (newCodeNumber > 9999)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }

        // 生成新的编码
        private string GenerateWarehouseCode(int codeNumber)
        {
            // 返回完整的编码，包括前缀 "CK" 和数字部分
            return "KH" + codeNumber.ToString("D4");
        }

        /// <summary>
        /// 客户列修改
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> updateClient(bs_client bsClient)
        {
            if (ModelState.IsValid)
            {
                int result = await _bs_clientService.Update(bsClient);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }

        }

        /// <summary>
        /// 客户列删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{client_id}")]
        public async Task<IActionResult> DeleteWarehouse(int client_id)
        {
            int result = await _bs_clientService.Delete(client_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }
        /// <summary>
        /// 客户分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<bs_client>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "client_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_client"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_client>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_client> fenYe = new FenYe<bs_client>()
                {
                    List = result,
                    Rows = row,
                };

                if (fenYe.List.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }
    }
    }

